//
//  AppPersistancy.swift
//  test-ios
//
//  Created by wyz5204 on 2023/4/1.
//

import Foundation

import GRDB

class AppPersistancy {
    
    
    public static let shared = AppPersistancy()
    
    private let dbQueue: DatabaseQueue
    private let dbPathUrl: URL
    init(){
        do {
            dbPathUrl = try FileManager.default.url(for: .applicationSupportDirectory,
                                                    in: .userDomainMask,
                                                    appropriateFor: nil,
                                                    create:true).appendingPathComponent("db.sqlite")
            print("setup Database" , dbPathUrl)
            dbQueue = try AppDatabase.openDB(dbPathUrl.path)
        } catch {
            fatalError()
        }
    }
    
    public func insertDBEntity(){
        print("insertDBEntity" , dbPathUrl)
        do {
            print("insertDBEntity start insert")
            try dbQueue.write({ database in
                var joke = Joke.DB(id : 1 ,reason: "reason", errorCode: 1)
                print(joke)
                do {
                    try joke.insert(database)
                }catch let insertError  {
                    print("nsertDBEntity >>1" ,insertError)
                }
            })
        }catch let writeError {
            print("insertDBEntity >>2" , writeError)
        }
    }
    
    
}
